<?php
Class URL {

	const POST		= 2;
	const GET		= 3;
	const PUT		= 4;
	const DELETE	= 5;

	protected $HTTPCode		= null;
	protected $timeout		= 30;
	protected $headers		= array();
	protected $fields		= array();
	protected $response		= null;
	protected $responseInfo	= array();
	protected $method		= URL::GET;
	protected $redirects	= 4;
	protected $follow		= true;

	public function getResponseHeaders($header) {
		return $this->getInfo($header);
	}

	public function getInfo($header = null) {
		if ($header) {
			return $this->responseInfo[$header];			
		} else {
			return $this->responseInfo;
		}
	}

	public function setRedirects($attempts) {
		$this->redirects = $attempts;
	}

	public function getRedirects() {
		return $this->redirects;
	}

	public function setFollow($boolean) {
		$this->follow = $boolean;
	}

	public function getFollow() {
		return $this->follow;
	}

	public function __construct($URL) {
		$this->curl = curl_init();
		curl_setopt($this->curl, CURLOPT_URL, $URL);
	}

	public function fetch() { 

		if ($this->method == URL::POST) {
			curl_setopt($this->curl, CURLOPT_POST, true);
			curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->fields);
			$this->setHeader("Content-Type", "application/x-www-form-urlencoded");
		}

		curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, $this->follow);
		curl_setopt($this->curl, CURLOPT_MAXREDIRS, $this->redirects);
		curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers);
		curl_setopt($this->curl, CURLOPT_HEADER, false);
		curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);

		$this->response = curl_exec($this->curl);
		$this->HTTPCode = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
		$this->info = curl_getinfo($this->curl);
		curl_close($this->curl);
	}

	public function setRequestMethod($method) {
		$this->method = $method;
	}

	public function getRequestMethod() {
		return $this->method;
	}

	public function setTimeout($seconds) {
		$this->timeout = $seconds;
	}

	public function getTimeout() {
		return $this->timeout;
	}

	public function getResponseCode() {
		return $this->HTTPCode;
	}

	public function setHeader($header, $value) {
		$this->headers[$header] = $value;
	}

	public function getHeader($header) {
		return $this->headers[$header];
	}

	public function getHeaders() {
		return $this->headers;
	}

	public function setField($field, $value) {
		$this->fields[$field] = urlencode($value);
	}

	public function getField($field) {
		return $this->fields[$field];
	}

	public function getFields() {
		return $this->fields;
	}

	public function getContent() {
		return $this->response;
	}

}